<?php
include_once("core/mapped.php");
include_once("models/maps/door.php");

/**
 * Map
 *
 * ModelClass mapped with map table to deal with a single map
 *
 * @copyright joel Simoes
 * @package models_maps
 */
class Map extends Mapped {
	public $table = "map";
	public $doorArray = array();
	public $doorPoint = null;
	/**
	 * Adds an user with request's vars
	 */
	public function __construct($mod,$key="id",$val="null") {
		parent::__construct($mod, $key, $val);
		if ($this->isOk())
		{
			$doors = new Doors();
			$this->doorArray = $doors->getDoorsComplex(" WHERE map_id = {$this->field->id}", "array");
		}

	}


	public function delete(){
		parent::delete();
		$doors = new Doors();
		$doorsRes = $doors->getDoorsComplex("WHERE id IN (SELECT d1.toid FROM door as d1 WHERE d1.toid = door.id AND d1.map_id = {$this->field->id})", "array");
		if (is_array($doorsRes) && count($doorsRes))
		foreach ($doorsRes as $tmpDoor)
		{
			$door = new Door("rw", "id", $tmpDoor->id);
			if ($door->isOk())
			{
				$door->field->toid = 0;
			}
			$door = null;
		}
		$queryDelDoors = "DELETE FROM door where map_id = {$this->field->id}";
		$this->database->queries($queryDelDoors);
	}

	/**
	 *
	 * @return array
	 */
	public function getDoorPoints()
	{
		if (!is_null($this->doorPoint)) return $this->doorPoint;
		$return = array();
		if (count($this->doorArray))
		foreach ($this->doorArray as $door)
		{
			$return[] = $door->point;
		}
		$this->doorPoint = $return;
		return $this->doorPoint;
	}

	public function addMap() {
		$tab = Array(
        "name"  => "name",
        "matrice" => "matrice",
        "file" => "file",
        "fullAlpha" => "fullAlpha"
        );
        $this->fromRequest($tab);
	}

	//not used i think
	public function getXML(){
		$tab = Array(
      "id"  => "mid",
      "name"  => "mname",
      "matrice" => "mmatrice",
      "file" => "mfile",
      "fullAlpha" => "mfullAlphe"
      );
      return $this->toXML("map",$tab);
	}

	public function resizeImage($imageWidth, $imageHeight, $newName = "")
	{


		if (is_file("mapFiles/{$this->field->file}"))
		{
			if ($newName == "") $newName = "mapFiles/{$this->field->file}";
			$fichier = "mapFiles/{$this->field->file}";

			$imageSrc			= new Imagick($fichier);
			$size 				= getimagesize($fichier);

			$ratio_x = $size[0] / $imageWidth;
			$ratio_y = $size[1] / $imageHeight;



			$ratioImage = min($ratio_x, $ratio_y);

			$size[0] = round($size[0]/$ratioImage);
			$size[1] = round($size[1]/$ratioImage);

			$imageSrc->adaptiveResizeImage($size[0], $size[1]);
			$imageSrc->cropImage($imageWidth, $imageHeight,0 ,0);

			//}
			/**
			else {
			$image			= imagecreatetruecolor($ratioImage, round(($ratioImage/$size[0])*$size[1]));
			imagecopyresampled($image, $imageSrc, 0, 0, 0, 0, $ratioImage, round($size[1]*($ratioImage/$size[0])), $size[0], $size[1]);
			}
			*/
			$fp = fopen($newName, "w+");
			fwrite($fp, $imageSrc);
			fclose($fp);

			if ($newName == "mapFiles/{$this->field->file}")
			{
				$this->decoupeMap(16, 12);
			}

			//$vignette = imagejpeg($imageSrc,"mapFiles/{$this->field->file}",50);
			//return $vignette;

		}
	}


	/**
	 *
	 * @param int $nbX
	 * @param int $nbY
	 * @return void
	 */
	public function decoupeMap($nbX, $nbY)
	{
		$nbX = round($nbX);
		$nbY = round($nbY);
		if (!$nbX || !$nbY) return;
		$folder = "mapFiles/{$this->field->id}";
		$fichier = "mapFiles/{$this->field->file}";
		if (!is_file($fichier)) return;
		if (is_dir($folder))
		{
			RemoveDir($folder);
		}

		mkdir($folder);
		$size 				= getimagesize($fichier);

		$sizeX = round($size[0]/$nbX);
		$sizeY = round($size[1]/$nbY);
		if (!$sizeX || !$sizeY) return;

		for ($i=0; $i < $nbX; $i++)
		{
			for ($j=0; $j < $nbY; $j++)
			{
				$imageSrc			= new Imagick($fichier);
				$imageSrc->cropImage($sizeX, $sizeY,$i*$sizeX ,$j*$sizeY);
				$fp = fopen("{$folder}/{$i}_{$j}.png", "w+");
				fwrite($fp, $imageSrc);
				fclose($fp);
			}
		}
		$this->genereMatrice($nbX, $nbY, $folder);
		//$this->fusionneImage($nbX, $nbY, $folder);

		// on ouvre une image

	}

	function genereMatrice($nbX, $nbY, $folder)
	{
		$this->field->matrice = "";
		$this->field->fullAlpha = "";
		$arrayCompare = array("red" => 0, "green" => 0, "blue" => 0);
		//$arrayCompare1 = array("red" => 255, "green" => 255, "blue" => 255, "alpha" => 0);
		//$arrayCompare = array("alpha" => 127);
		$matrice = array();
		for ($i = 0; $i < $nbY; $i++ )
		{
			for ($j=0; $j < $nbX; $j++)
			{
				$fichier = "{$folder}/{$j}_{$i}.png";
				$isFree = 1;
				$im = imagecreatefrompng($fichier);
				$size  = getimagesize($fichier);
				// on obtient une couleur

				$noFree = 0;

				for ($k = 0; $k < $size[0]; $k++)
				{
					for ($l = 0; $l < $size[1]; $l++)
					{
						$color_index = imagecolorat($im, $k, $l);

						$color_tran = imagecolorsforindex($im, $color_index);
						//echo "<pre>".print_r($color_tran, true)."</pre>";


						foreach ($arrayCompare as $key => $value )
						{
							$inMin = min(round($arrayCompare[$key]) - 10, round($color_tran[$key]));
							$inMax = max(round($arrayCompare[$key]) + 10, round($color_tran[$key]));
							if ($inMin == $color_tran[$key] || $inMax == $color_tran[$key])
							{
								$noFree++;
								/**
								 echo "<pre>".print_r($color_tran, true)."</pre>";
								 echo "<pre>".print_r($arrayCompare, true)."</pre>";
								 echo "<pre>$key</pre>";
								 echo "<pre>{$inMin} = min(round({$arrayCompare[$key]}) - 10, round({$color_tran[$key]}))</pre>";
								 echo "<pre>{$inMax} = max(round({$arrayCompare[$key]}) + 10, round({$color_tran[$key]}))</pre>";
								 die();
								 */
							}
						}

					}
				}
				$totalFree = $size[0]*$size[1];
				if ($totalFree)
				{
					if (round($noFree / $totalFree * 100) > 30) $isFree = 0;
					if (round($noFree / $totalFree * 100) <= 2) $this->field->fullAlpha .= "{$j}_{$i};";
				}
				$matrice[$i][$j] = $isFree;
				$this->field->matrice .= "[{$isFree}]-";
			}
			if (substr($this->field->matrice, -1) == "-")
			{
				$this->field->matrice = substr($this->field->matrice, 0, -1);
			}
			$this->field->matrice .= "\n";
		}
		if (substr($this->field->matrice, -1) == "\n")
		{
			$this->field->matrice = substr($this->field->matrice, 0, -1);
		}

	}


	function fusionneImage($nbX, $nbY, $folder)
	{

		$fullAlpha = explode(";",$this->field->fullAlpha);
		//echo "<pre>".print_r($fullAlpha, true)."</pre>";
		for ($i = 0; $i < $nbY; $i++ )
		{
			for ($j=0; $j < $nbX; $j++)
			{
				$fichier = "{$folder}/{$j}_{$i}.png";
					

				$newImage = imagecreatefrompng($fichier);
				$fond = imagecreatefrompng("fonds/grass.png");
				if (!in_array("{$j}_{$i}", $fullAlpha))
				{
					imagecopy($fond, $newImage, 0, 0, 0, 0, 50, 50);
				}
				imagepng($fond, $fichier);
				imagedestroy($newImage);
				imagedestroy($fond);
					


			}



		}

	}

	function resetFond($x, $y)
	{
		$fond = imagecreatefrompng("fonds/grass.png");

		$folder = "mapFiles/{$this->field->id}";
		$fichier = "{$folder}/{$x}_{$y}.png";
		imagepng($fond, $fichier);
		imagedestroy($fond);
	}
}

/**
 * Users
 *
 * Class dealing with a group of Maps (instances of ModelClass_Map)
 *
 * @copyright joel Simoes
 * @version 01
 * @package models_maps
 */
class Maps extends Normal{

	/**
	 * Retrieves the list of Maps
	 * @return $MapsNode the node containing all maps
	 */
	public function getMaps() {
		$MapsNode = $this->response->doc->createElement("maps");
		$doors = new Doors();
		$req       = "SELECT * FROM `map`;";
		$result    = $this->database->queries($req);

		while($obj = $result->fetch_object()) {
			$MapNode = null;
			$tab = array(
	        "id"=>"id",
	        "name" => "name",
	        "matrice"=>"matrice",
	        "file"=>"file",
	        "fullAlpha"=>"fullAlpha"
	        );
	        $MapNode = $this->response->mapObjectXML ($obj, "map", $tab);
	        $doorsNode = $doors->getDoorsComplex("WHERE map_id = {$obj->id}");
	        $MapNode->appendChild($doorsNode);
	         
	        $MapsNode->appendChild($MapNode);
		}

		return $MapsNode;
	}

	/**
	 * Retrieves a range of the list of Maps
	 * @param string filter (sql filter)
	 * @return DOMElement $MapsNode
	 */
	public function getMapsComplex($sql, $returnType = "xml") {
		$return = array();
		$MapsNode = $this->response->doc->createElement("maps");
		$doors = new Doors();

		$req       = "SELECT * FROM `map` ".$sql.";";
		$result    = $this->database->queries($req);
		if($result != FALSE){
			while($obj = $result->fetch_object()) {
				$MapNode = null;
				$tab = array("id"=>"id", "name" => "name", "matrice"=>"matrice", "file"=>"file", "fullAlpha"=>"fullAlpha");
				$return[] = $obj;
				$MapNode = $this->response->mapObjectXML($obj, "map", $tab);
				$doorsNode = $doors->getDoorsComplex("WHERE map_id = {$obj->id}");
				$MapNode->appendChild($doorsNode);
				$MapsNode->appendChild($MapNode);
			}
		}
		if ( $returnType == "array") return $return;
		return $MapsNode;
	}

	/**
	 * Returns the number of users filtered
	 * @param string sql filter
	 * @return the number of users
	 */
	public function getNumMaps($sql){
		$sqlCount = "SELECT COUNT(id) FROM `map` ".$sql;
		$result   = $this->database->queries($sqlCount);
		$array    = $result->fetch_array();

		return $array[0];
	}
}

?>
